package data_structures_and_algorithms.list_node;

import common.ListNode;

/**
 * @ClassName Code_0141_hasCycle_InListNode
 * @Description: https://leetcode.cn/problems/linked-list-cycle/
 * @Author: myl
 * @create_time: 2022/10/27 23:36
 */
public class Code_0141_hasCycle_InListNode {


    /**
     * 方案一：创建Set存储，遍历到发现存在即存在环形链表
     *
     * 方案二：创建快慢指针，如果二者能相遇，则证明存在环形链表
     */

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        ListNode slow = head.next, fast = head.next.next;

        while (true){
            if (slow == fast)
                return true;
            if (fast == null || fast.next == null)
                return false;
            slow = slow.next;
            fast = fast.next.next;
        }
    }
}
